package org.serg.transcards;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import android.R.bool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	//cover img
	private Drawable back_image;
	//cover trup
	private Drawable trup_image;
	//imgs of zombi
	private Map<Integer, Drawable> zomb_images;
	//imgs of characters
	private List<Drawable> char_images;
	//list of games (static)
	private Map<Integer, Card> games;
	//list of models, for each cell (dinamic)
	private Map<Integer, Card> cards;
	//list of cell variants, for mix
	private List<Integer> game_variants;
	//num of current games
	private int game_num;
	
	//choosed cell
	private Card current_card;
	//attempt num in the current game
	private int attempt;
	//sum of scores for all games
	private int score;
	
	private TextView score_text;
	private TableLayout main_table;
	private Context context;
	private ButtonListener button_listener;
	private static Object lock = new Object();
	
	//timer handler for click on cell
	private UpdateCardsHandler handler1;
	//timer handler befor start of game 
	private StartGameHandler handler2;
	
	private Intent intent;
	private static final int MAIN_ACTIVITY = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		//cover img
		back_image = getResources().getDrawable(R.drawable.back);
		//score
		score_text = (TextView) findViewById(R.id.ScoreText);
		//trup
		trup_image = getResources().getDrawable(R.drawable.trup);

		handler1 = new UpdateCardsHandler();
		handler2 = new StartGameHandler();
		button_listener = new ButtonListener();
		
		main_table = (TableLayout) findViewById(R.id.TableLayout01);
		context = main_table.getContext();
		
		intent = new Intent(this, OverActivity.class);

		initGame();
	}
	
	private void initGame() {
		findViewById(R.id.CharacterImage01).setBackgroundDrawable(back_image);
		findViewById(R.id.CharacterImage02).setBackgroundDrawable(back_image);
		findViewById(R.id.CharacterImage03).setBackgroundDrawable(back_image);
		findViewById(R.id.CharacterImage04).setBackgroundDrawable(back_image);
		findViewById(R.id.CharacterImage05).setBackgroundDrawable(back_image);
		
		char_images = new ArrayList<Drawable>();
		char_images.add(getResources().getDrawable(R.drawable.c0));
		char_images.add(getResources().getDrawable(R.drawable.c1));
		char_images.add(getResources().getDrawable(R.drawable.c2));
		char_images.add(getResources().getDrawable(R.drawable.c3));
		char_images.add(getResources().getDrawable(R.drawable.c4));
		
		//avalable characters 
		zomb_images = new HashMap<Integer, Drawable>();
		zomb_images.put(0, getResources().getDrawable(R.drawable.z0));
		zomb_images.put(1, getResources().getDrawable(R.drawable.z1));
		zomb_images.put(2, getResources().getDrawable(R.drawable.z2));
		zomb_images.put(3, getResources().getDrawable(R.drawable.z3));
		zomb_images.put(4, getResources().getDrawable(R.drawable.z4));
		zomb_images.put(5, getResources().getDrawable(R.drawable.z5));
		zomb_images.put(6, getResources().getDrawable(R.drawable.z6));
		zomb_images.put(7, getResources().getDrawable(R.drawable.z0));
		zomb_images.put(8, getResources().getDrawable(R.drawable.z1));
		zomb_images.put(9, getResources().getDrawable(R.drawable.z2));
		zomb_images.put(10, getResources().getDrawable(R.drawable.z3));
		zomb_images.put(11, getResources().getDrawable(R.drawable.z4));
		zomb_images.put(12, getResources().getDrawable(R.drawable.z5));
		zomb_images.put(13, getResources().getDrawable(R.drawable.z6));
		zomb_images.put(14, getResources().getDrawable(R.drawable.z0));
		zomb_images.put(15, getResources().getDrawable(R.drawable.z1));
		zomb_images.put(16, getResources().getDrawable(R.drawable.z2));
		zomb_images.put(17, getResources().getDrawable(R.drawable.z3));
		zomb_images.put(18, getResources().getDrawable(R.drawable.z4));
		zomb_images.put(19, getResources().getDrawable(R.drawable.z5));
		
		
				
		//mix imgs list 
		List<Drawable> tmp_images = char_images;
		long seed = System.nanoTime();
		Collections.shuffle(tmp_images, new Random(seed));
		games = new HashMap<Integer, Card>();
		games.put(0, new Card((ImageView) findViewById(R.id.CharacterImage01), tmp_images.get(0), 0, false));
		games.put(1, new Card((ImageView) findViewById(R.id.CharacterImage02), tmp_images.get(1), 1, false));
		games.put(2, new Card((ImageView) findViewById(R.id.CharacterImage03), tmp_images.get(2), 2, false));
		games.put(3, new Card((ImageView) findViewById(R.id.CharacterImage04), tmp_images.get(3), 3, false));
		games.put(4, new Card((ImageView) findViewById(R.id.CharacterImage05), tmp_images.get(4), 4, false));

		//create variants for mix
		game_variants = new ArrayList<Integer>();
		for (int i=0; i<25; i++) {
			game_variants.add(i);
		}	
				
		game_num = 0;
		score = 0;
		
		newGame();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		Toast.makeText(getApplicationContext(),
				"Return from Over Activity ", Toast.LENGTH_LONG).show();
		
		// check which activity gives data
		switch (requestCode) {
		// checking for our DetailActivity using request code
		case MAIN_ACTIVITY:
			// check whether result comes with RESULT_OK (That mean no problem
			// in result)
			if (resultCode == RESULT_OK) {
				
				String action = data.getExtras().getString("action");
				System.out.println("action: "+action);
				
				if (action.equals("continue")) {
					initGame();
				} else {
					System.exit(RESULT_OK);
				}
			}
		}
	}


	private void newGame() {
		score_text.setText("score: " + Integer.toString(score));
		if (game_num > 4) {
			Iterator it = cards.entrySet().iterator();
		    while (it.hasNext()) {
		        Map.Entry map_entry = (Map.Entry) it.next();
		        Card item = (Card) map_entry.getValue();
		        
		        item.access = false;
			}
		    intent.putExtra("score", Integer.toString(score));
		    startActivityForResult(intent, MAIN_ACTIVITY);
		    return;
		}
		int ROW_COUNT = 5;
		int COL_COUNT = 5;
		
		cards = new HashMap<Integer, Card>();
		
		//mix variant list 
		List<Integer> variants = game_variants;
		long seed = System.nanoTime();
		Collections.shuffle(variants, new Random(seed));
		
		for(int item: variants) {
			System.out.println("test "+Integer.toString(item));
		}
		
		TableRow tr = ((TableRow) findViewById(R.id.TableRow01));
		tr.removeAllViews();
		main_table = new TableLayout(context);
		tr.addView(main_table);

		for (int y = 0; y < ROW_COUNT; y++) {
			TableRow row = new TableRow(context);
			row.setHorizontalGravity(Gravity.CENTER);

			for (int x = 0; x < COL_COUNT; x++) {
				int index = (y * ROW_COUNT) + x;

				int key = variants.get(index);
				Drawable img;
				boolean zombi = false;
				if (key<5) {
					//if not zombi
					Card game_card = games.get(key);
					img = game_card.getImage();
				} else {
					img = zomb_images.get(key-5);
					zombi = true;
				}
				
				
				ImageView cell = new ImageView(context);
				//cell.setBackgroundDrawable(backImage);
				cell.setBackgroundDrawable(img);
				cell.setId(index);
				cell.setOnClickListener(button_listener);
				row.addView(cell);
				
				Card card = new Card(cell, img, key, zombi);
				cards.put(index, card);
			}

			main_table.addView(row);
		}
		
		TimerTask tt = new TimerTask() {
			@Override
			public void run() {
				try {
					handler2.sendEmptyMessage(0);
				} catch (Exception e) {
					Log.e("E1", e.getMessage());
				}
			}
		};

		Timer t = new Timer(false);
		t.schedule(tt, 5000);
		
		current_card = null;
		attempt = 0;
	}
	
	class StartGameHandler extends Handler {

		@Override
		public void handleMessage(Message msg) {
			Iterator it = cards.entrySet().iterator();
		    while (it.hasNext()) {
		        Map.Entry map_entry = (Map.Entry) it.next();
		        Card item = (Card) map_entry.getValue();
		        
		        ImageView cell = item.cell;
				//cell.setBackgroundDrawable(item.getImage());
				cell.setBackgroundDrawable(back_image);
				item.access = true;
		    }
		    
		    Card game_card = games.get(game_num);
		    ImageView cell = game_card.cell;
			cell.setBackgroundDrawable(game_card.getImage());
		}
	}

	class ButtonListener implements OnClickListener {

		@Override
		public void onClick(View v) {

			int id = v.getId();
			Card card = cards.get(id);
			if (!card.access) {
				return;
			}
			ImageView cell = card.cell;
			cell.setBackgroundDrawable(card.getImage());
			current_card = card;
			
			Iterator it = cards.entrySet().iterator();
		    while (it.hasNext()) {
		        Map.Entry map_entry = (Map.Entry) it.next();
		        Card item = (Card) map_entry.getValue();
		        
		        item.access = false;
			}
			
			TimerTask tt = new TimerTask() {

				@Override
				public void run() {
					try {
						handler1.sendEmptyMessage(0);
					} catch (Exception e) {
						Log.e("E1", e.getMessage());
					}
				}
			};

			Timer t = new Timer(false);
			t.schedule(tt, 1300);
			
		}
	}

	class UpdateCardsHandler extends Handler {

		@Override
		public void handleMessage(Message msg) {
			Card game_card = games.get(game_num);
			
			Iterator it = cards.entrySet().iterator();
		    while (it.hasNext()) {
		        Map.Entry map_entry = (Map.Entry) it.next();
		        Card item = (Card) map_entry.getValue();
		        
		        item.access = true;
			}
			
		    // if find character, incr score, and start new gane 
		    if (current_card.key == game_card.key) {
				game_num++;
				score++;
				newGame();
				return;
				
			}
		    
		    // if cell is not zombi, just continue
		    if (!current_card.zombi) {
		    	current_card = null;
		    	return;
		    }
		    
		    // if current cell is zombi, decr attempt and continue 
	    	if (attempt<2) {
				attempt++;
				current_card = null;
				return;
			} 
	    	// if current cell is zombi, and nothing to decr, die person and new game
	    	else { 
	    		ImageView cell = game_card.cell;
	    		cell.setBackgroundDrawable(trup_image);
	    		game_num++;
	    		newGame();
	    	}
	    		
		}
	}
	
}
